import re

from netmiko.huawei.huawei import HuaweiSSH
from netmiko import NetMikoTimeoutException
from netmiko import NetMikoAuthenticationException
from getpass import getpass

username = "yunwei-xunjian"
password = "Rn%kmh4s,4"
ips = ["10.2.161.3"]

cmd_line = ['display version', 'display cpu-usage', 'display memory-usage', 'display device']

# 打开ip_list.txt文件获取IP列表
# ip_list = open('ip_list.txt', 'r')
# ip_addr = ip_list.readlines()
# ip_list.close()

for ip in ips:
    print('本次巡检的设备IP：' + ip)
    try:
        switch = {
            'device_type': 'huawei',
            'ip': ip,
            'username': username,
            'password': password,
        }

        net_connect = HuaweiSSH(**switch)
        print("恭喜，ssh成功登录")
        print("设备名：" + str(net_connect.find_prompt().strip('<>')))
        net_connect.send_command("screen-length 0 temporary")
        for cmd in cmd_line:
            cmd_result = net_connect.send_command(cmd)
            regex_str = []
            if 'VRP (R) software' in cmd_result:
                regex_str = '\(\w*\d\d.*\)'
                version = (re.search(regex_str, cmd_result))
                label = version.group().strip('()')
                print("版本: ",label)
                cmd_result = ''
            if 'CPU ' in cmd_result:
                regex_str = '\d*.\d*.\%'
                cpu_usage = (re.search(regex_str, cmd_result))
                label=cpu_usage.group().strip(' ')
                print("CPU使用率: ",label)
                cmd_result = ''
            if 'Memory ' in cmd_result:
                regex_str = '\d*.\%'
                memory = (re.search(regex_str, cmd_result))
                label = memory.group()
                print("内存使用率: ",label)
                cmd_result = ''
            if 'Device ' in cmd_result:
                if 'Abnormal' in cmd_result:
                    print("状态: Abnormal")
                elif 'WrongType' in cmd_result:
                    print("状态: WrongType")
                elif 'Unregistered' in cmd_result:
                    print("状态: Unregistered")
                elif 'Off' in cmd_result:
                    print("状态: Off")
                elif 'Offline' in cmd_result:
                    print("状态: Offline")
                else:
                    print("状态: Normal")
                cmd_result = ''


        net_connect.disconnect()
    except (EOFError, NetMikoTimeoutException):
        print('无法连接设备')
        netmikotimeout = (u'无法连接设备' + ip)
    except (EOFError, NetMikoAuthenticationException):
        print('用户名密码错误!')
        netmikotuehenticattion = (u'用户名密码错误' + ip)
